package com.zlyx.easy.swagger.plugins;

import static springfox.documentation.swagger.common.SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER;
import static springfox.documentation.swagger.common.SwaggerPluginSupport.pluginDoesApply;

import java.util.Optional;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ValueConstants;

import com.zlyx.easy.core.utils.StringUtils;

import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.ParameterContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER)
public class EasySwaggerRequestParamParameterBuilder implements ParameterBuilderPlugin {

	@Override
	public void apply(ParameterContext context) {
		String name = context.resolvedMethodParameter().defaultName().get();
		Optional<RequestParam> requestParam = context.resolvedMethodParameter().findAnnotation(RequestParam.class);
		if (requestParam.isPresent()) {
			if (StringUtils.isNotEmpty(requestParam.get().value())) {
				name = requestParam.get().value();
			} else if (StringUtils.isNotEmpty(requestParam.get().name())) {
				name = requestParam.get().name();
			}
			if (!ValueConstants.DEFAULT_NONE.equals(requestParam.get().defaultValue())) {
				context.parameterBuilder().defaultValue(requestParam.get().defaultValue());
			}
			context.parameterBuilder().name(name).parameterAccess("access").required(requestParam.get().required())
					.order(SWAGGER_PLUGIN_ORDER);
		}
	}

	@Override
	public boolean supports(DocumentationType delimiter) {
		return pluginDoesApply(delimiter);
	}
}
